package com.mercadoutils.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.AuthorizationFailure;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;

@Controller
public class StockController {
	
	@RequestMapping("/StockUpdate.html")
	 public String doRedirect(Model model) throws AuthorizationFailure, MeliException, IOException
	 {
		
        HttpSession session = SesionListener.getSession();
        Meli m = (Meli) session.getAttribute("meli");
        
        
        FluentStringsMap params = new FluentStringsMap();
        params.add("access_token", m.getAccessToken());
        Response r = m.get("/users/me",params);
		String resultado = r.getResponseBody().toString(); 
		JsonElement jelement = new JsonParser().parse(resultado); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    
	    params.clear();
	    params.add("seller_id", jobject.get("id").toString());
	    
	    r = m.get("/sites/MLA/search",params);
	    
	    
	    resultado = r.getResponseBody().toString();
	    jelement = new JsonParser().parse(resultado); 
	    jobject = jelement.getAsJsonObject();
	    System.out.println(jobject.toString());
	    JsonObject jsonPaginas = jobject.getAsJsonObject("paging");
//	    System.out.println(jsonPaginas.toString());
	    JsonArray jsonResults = jobject.getAsJsonArray("results");
//	    System.out.println(jsonResults.toString());
	    
	    String result = "";
	    for(int i=0;i<jsonResults.size();i++){
	    	result+=unMarshall(jsonResults.get(i).getAsJsonObject());
	    }
	    
	    model.addAttribute("rows",result);
	    model.addAttribute("nombre",session.getAttribute("nombre"));
	    model.addAttribute("apellido",session.getAttribute("apellido"));
	    model.addAttribute("role",session.getAttribute("role"));
	    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
		return "stockUpdate";
	 }
	
	@RequestMapping("/stockUpdateValues.html")
	 public String doStockPut(@RequestParam("json") String jsonStock,Model model) throws AuthorizationFailure, MeliException, IOException, InterruptedException
	 {
		
		HttpSession session = SesionListener.getSession();
		Meli m = (Meli) session.getAttribute("meli");
		
		JsonElement jelement = new JsonParser().parse(jsonStock); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    JsonArray jArray = jobject.getAsJsonArray("array");
	    
	    FluentStringsMap params = new FluentStringsMap();
		params.add("access_token", m.getAccessToken()); 
	    
	    for(int i=0;i<jArray.size();i++){
	    	jobject= jArray.get(i).getAsJsonObject();
	    	Response r = m.put("/items/"+jobject.get("id").getAsString(), params, "{\"available_quantity\":"+jobject.get("value").getAsInt()+"}");
	    	System.out.println(r.getResponseBody().toString());
	    }
	    	
//		m.put("/items/"++"/status", params, "{\"status\":\"closed\"}");
		
	    model.addAttribute("nombre",session.getAttribute("nombre"));
	    model.addAttribute("apellido",session.getAttribute("apellido"));
	    model.addAttribute("role",session.getAttribute("role"));
	    model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
	    Thread.currentThread().sleep(2000);
	    return "redirect:/StockUpdate.html";
	 }
	
	private String unMarshall(JsonObject jobject){
    	String result = "";
    	result+="<tr><td>"+jobject.get("title").toString()+"</td>";
    	result+="<td>"+jobject.get("price").toString()+"</td>";
    	result+="<td>"+jobject.get("condition").toString()+"</td>";
    	result+="<td>"+jobject.get("sold_quantity").toString()+"</td>";
    	result+="<td><input type=\"text\" name=\"fname\" id=\""+jobject.get("id").getAsString()+"\" value=\""+jobject.get("available_quantity").toString()+"\" onchange=\"addToArray('"+jobject.get("id").getAsString()+"');\"></td>";
    	result+="</tr>";
    	return result;
    }


}
